// 验证处理程序
import { generateToken, verifyToken } from '../utils/jwt';
import { nanoid } from 'nanoid';
import { SQL_QUERIES, executeQuery } from '../sql/sql';

export const handleVerification = {
  // 查询验证状态
  async checkStatus(request, env) {
    try {
      // 从Authorization header获取token
      const authHeader = request.headers.get('Authorization');
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return new Response(JSON.stringify({
          code: 401,
          message: '未授权访问'
        }), { status: 401 });
      }

      // 验证token
      const token = authHeader.split(' ')[1];
      const decoded = await verifyToken(token, env.jwtSecretLoginAPP);
      if (!decoded || !decoded.openid) {
        return new Response(JSON.stringify({
          code: 401,
          message: 'token无效'
        }), { status: 401 });
      }
      
      // 查询验证请求
      const result = await executeQuery(
        env.MY_LOGINAPP_DB, 
        {
          sql: SQL_QUERIES.getVerificationRequest.sql,
          requireAuth: false
        },
        [decoded.openid]
      );
      
      if (!result.success) {
        throw new Error('Failed to get verification request: ' + result.error);
      }

      if (!result.data) {
        return new Response(JSON.stringify({
          code: 404,
          message: '未找到验证记录'
        }));
      }
      
      return new Response(JSON.stringify({
        code: 200,
        data: {
          status: result.data.verification_status,
          method: result.data.verification_method,
          identifier: result.data.request_identifier
        }
      }));
    } catch (error) {
      console.error('Check verification status error:', error);
      return new Response(JSON.stringify({
        code: 500,
        message: 'Internal Server Error',
        error: error.message
      }), { status: 500 });
    }
  },

  // 发起验证请求
  async request(request, env) {
    try {
      // 从Authorization header获取token
      const authHeader = request.headers.get('Authorization');
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return new Response(JSON.stringify({
          code: 401,
          message: '未授权访问'
        }), { status: 401 });
      }

      // 验证token
      const token = authHeader.split(' ')[1];
      const decoded = await verifyToken(token, env.jwtSecretLoginAPP);
      if (!decoded || !decoded.openid) {
        return new Response(JSON.stringify({
          code: 401,
          message: 'token无效'
        }), { status: 401 });
      }

      const { type, value, platform } = await request.json();
      
      // 生成验证码和请求ID
      const verificationCode = Math.random().toString().slice(2, 8);
      const code = nanoid(16); // 生成唯一的验证请求编号
      
      // 存储验证请求
      const result = await executeQuery(
        env.MY_LOGINAPP_DB, 
        {
          sql: SQL_QUERIES.createVerificationRequest.sql,
          requireAuth: false
        },
        [
          code,
          platform,
          value,
          type,
          verificationCode,
          'pending',
          decoded.openid,
          'system'
        ]
      );

      if (!result.success) {
        throw new Error('Failed to create verification request: ' + result.error);
      }
      
      // TODO: 发送验证码到手机或邮箱
      
      return new Response(JSON.stringify({
        code: 200,
        data: {
          requestId: code,
          expireIn: 300
        }
      }));
    } catch (error) {
      console.error('Verification request error:', error);
      return new Response(JSON.stringify({
        code: 500,
        message: 'Internal Server Error',
        error: error.message
      }), { status: 500 });
    }
  },

  // 验证码校验
  async verify(request, env) {
    try {
      // 从Authorization header获取token
      const authHeader = request.headers.get('Authorization');
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return new Response(JSON.stringify({
          code: 401,
          message: '未授权访问'
        }), { status: 401 });
      }

      // 验证token
      const token = authHeader.split(' ')[1];
      const decoded = await verifyToken(token, env.jwtSecretLoginAPP);
      if (!decoded || !decoded.openid) {
        return new Response(JSON.stringify({
          code: 401,
          message: 'token无效'
        }), { status: 401 });
      }

      const { requestId, code } = await request.json();
      
      // 从数据库获取验证请求
      const result = await executeQuery(
        env.MY_LOGINAPP_DB, 
        {
          sql: SQL_QUERIES.getPendingVerification.sql,
          requireAuth: false
        },
        [requestId, decoded.openid]
      );
      
      if (!result.success) {
        throw new Error('Failed to get verification request: ' + result.error);
      }

      if (!result.data) {
        return new Response(JSON.stringify({
          code: 400,
          message: '验证请求不存在或已过期'
        }));
      }
      
      // 检查验证码
      if (result.data.verification_code !== code) {
        return new Response(JSON.stringify({
          code: 400,
          message: '验证码错误'
        }));
      }
      
      // 更新验证状态
      const updateResult = await executeQuery(
        env.MY_LOGINAPP_DB, 
        {
          sql: SQL_QUERIES.updateVerificationStatus.sql,
          requireAuth: false
        },
        [
          'approved',
          request.headers.get('CF-Connecting-IP') || '',
          decoded.openid, // verification_by
          requestId,
          decoded.openid
        ]
      );

      if (!updateResult.success) {
        throw new Error('Failed to update verification status: ' + updateResult.error);
      }
      
      // 生成验证通过的令牌
      const newToken = await generateToken({
        type: result.data.verification_method,
        identifier: result.data.request_identifier,
        platform: result.data.request_platform,
        openid: decoded.openid
      }, env.jwtSecretLoginAPP);
      
      return new Response(JSON.stringify({
        code: 200,
        data: { token: newToken }
      }));
    } catch (error) {
      console.error('Verification verify error:', error);
      return new Response(JSON.stringify({
        code: 500,
        message: 'Internal Server Error',
        error: error.message
      }), { status: 500 });
    }
  }
};
